<template lang="pug">
  master-layout
    div.login-w(slot="main")
      logo.logo
      div.instructions
        | 使用指南：
        br
        | 1.请阅卷人使用本人姓名及密码进入系统。
        br
        | 2.全体阅卷人员应当以高度负责的精神，公平、公正地做好阅卷工作。
      div.form-w
        div.form-w--mn
          el-form.kalix-form(v-bind:model="loginForm" v-bind:rules="rules" ref="loginForm" v-bind:show-message="false" label-width="90px")
            div.error-message {{error.message}}
            el-form-item.kalix-form-item(prop="name" label="用户名 :")
              el-input(v-model="loginForm.name" v-on:keyup="" placeholder="请输入用户名" ref="loginFormName")
                i.icon-users(slot="prefix")
            el-form-item.kalix-form-item(prop="pass" label="密码 :")
              el-input(type="password" v-model="loginForm.pass" ref="loginFormPass" placeholder="请输入密码" auto-complete="off")
                i.icon-lock(slot="prefix")
            el-form-item(label="")
              el-button.kalix-form--button(@click="onSubmit")
</template>

<script type="text/ecmascript-6">
  import MasterLayout from '../layout/Master'
  import Logo from '../components/Logo'
  import Login from '../api/login'
  import {checkFolder, createFolder} from '../config/utils'
  // import AdmZip from 'adm-zip'
  // import fs from 'fs'
  //  import nodeCmd from 'node-cmd'

  export default {
    data() {
      return {
        loginForm: {
          name: '',
          pass: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          pass: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ]
        },
        error: {
          flag: false,
          message: ''
        },
        folderName: 'ExamYueJuan',
        materialFolderUrl: null,
        zipFileName: '1234567',
        zipFileNameExt: '.zip'
      }
    },
    components: {
      MasterLayout,
      Logo
    },
    mounted() {
      this.$http.get('/logout')
      this.$KalixCatch.clear()
    },
    methods: {
      /**
       * 提交表单
       */
      onSubmit() {
        if (this._validateForm()) {
          this.login()
        }
      },
      /**
       * 登录提示
       * @param text
       * @param lock
       * @returns {*}
       */
      loadingTools(text, lock = true) {
        return this.$loading({
          lock,
          text,
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.4)'
        })
      },
      /**
       * 登录
       */
      login() {
        let l1 = this.loadingTools('登录授权')
        //  登录
        Login.remoteLogin({
          'username': this.loginForm.name,
          'password': this.loginForm.pass
        }).then(data => {
          l1.close()
          if (data.success) {
            this.userId = data.user.id
            this.$KalixCatch.save('id', this.userId)
            this.$KalixCatch.save('access_token', data.access_token)
            this.$KalixCatch.save('user_token', data.user.token)
            this.$KalixCatch.save('user_name', data.user.name)
            this.$KalixCatch.save('loginname', this.loginForm.name)
            // 在缓存中记录最后登录时间，处理单用户登录需求
            let now = new Date().getTime()
            this.$KalixCatch._saveLocal('lastLoginTime', now)
            this.$KalixCatch.save('lastLoginTime', now)
            data.user.loginname = this.loginForm.name
            console.log('\'[ ===== 2019年3月7日14:03:16 ===== ] Login OK!')
            // 登录成功
            // 检查考试
            // 分配考试目录
            this._createWorkFolder(`${window.KalixConfig.tmpFolder}`, () => {
              this.$KalixCatch.save('USER_INFO', JSON.stringify({
                userId: this.userId,
                loginname: this.loginForm.name,
                folderName: this.folderName,
                currentUser: data.user
              }))
              // this.$router.replace({name: 'QuestionsList'})
              this.$router.replace({name: 'SubjectList'})
            })
          } else {
            this.$refs.loginFormName.focus()
            this.$KalixMessage.error(data.message)
          }
        }).catch(error => {
          this.$alert('登录失败', '消息')
          l1.close()
          console.log('login error ', error)
          this.$refs.loginFormName.focus()
          this.$KalixMessage.error(error.message)
        })
      },
      _validateForm() {
        //  验证表单
        for (let key in this.rules) {
          this.error.flag = false
          this.error.message = ''
          this.$refs.loginForm.validateField(key, errorMessage => {
            //  如果错误信息长度 > 0 表示验证不通过
            this.error.flag = errorMessage.length > 0
            this.error.message = errorMessage
          })
          setTimeout(() => {
            this.error.message = ''
          }, 1500)
          if (this.error.flag) {
            return false
          }
        }
        return true
      },
      /**
       * 创建目录
       * @param callBack
       * @returns {Promise<void>}
       */
      async _createWorkFolder(folderUrl, callBack) {
        let flag = await checkFolder(folderUrl)
        if (!flag) {
          let f = await createFolder(folderUrl)
          if (f) {
            console.log('1f')
          }
          callBack()
        } else {
          callBack()
        }
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

  .login-w
    width 637px
    margin 0 auto
    .logo
      margin-top 111px
    .instructions
      color #ff0000
      font-size 14px
      line-height 24px
      margin-top 50px
    .form-w
      height 242px
      overflow hidden
      margin-top 48px
      background url("../assets/images/login-form-bg.png") 0 0 no-repeat
    .kalix-form
      width 350px
      margin 22px auto 0
      .error-message
        font-size 14px
        color #ff0000
        text-align right
        line-height 14px
        height 14px
        margin-bottom 6px
      .kalix-form--button
        border 0
        width 137px
        height 30px
        background url("../assets/images/submit-button-bg.png") 0 0 no-repeat
</style>
